<template>
  <slot :setVisible="setVisible" name="trigger">
    <!-- <el-button type="primary" @click="dialogVisible = true">创建项目</el-button> -->
  </slot>
  <el-dialog v-model="dialogVisible" @open="open" :title="props.title" width="600px"  :close-on-click-modal="false">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-suffix=":">
      <el-form-item label="业务类型" prop="busType">
        <el-select style="width: 100%;" v-model="form.busType"     placeholder="请选择业务类型"  :disabled="readOnly">
          <el-option v-for="dict in businessTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目标题" prop="name">
        <el-input v-model="form.name" :disabled="isEdit" maxlength="20" show-word-limit  placeholder="请选择用工项目或发放类型标题(限20字)" />
      </el-form-item>
      <el-form-item label="所属行业" prop="industry">
        <el-cascader
          ref="cascaderRef"
           placeholder="请选择行业"
          :emitPath="true"
          style="width: 100%;"
          v-model="form.industry"
          :show-all-levels="true"
          @change="handleChange"
          :disabled="isEdit"
          :options="industryOptions || []"
        />
      </el-form-item>
      <el-form-item label="项目类型" prop="classify">
        <el-radio-group :disabled="disabled || readOnly" v-model="form.classify"  @change="radioGroupChangeHandler">
          <el-radio :label="1">派单</el-radio>
          <el-radio :label="2">抢单</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="form.classify === 1">
        <el-form-item label="项目总金额"  prop="costMax">
            <el-col :span="11">
              <el-input-number :disabled="disabled || readOnly"  placeholder="请输入最小金额(元)" style="width: 100%;" controls-position="right" v-model="form.cost" />
            </el-col>
            <el-col style="text-align: center;" :span="2">~</el-col>
            <el-col :span="11">
              <el-input-number :disabled="disabled || readOnly" placeholder="请输入最大金额(元)" style="width: 100%;" controls-position="right" v-model="form.costMax" />
            </el-col>
        </el-form-item>
      </template>

      <el-form-item label="项目总金额"  prop="cost"   v-else>
        <el-input-number
          :disabled="disabled"
          style="width: 100%;"
          controls-position="right"
          placeholder="请输入项目总金额(元)"
          v-model="form.cost"
        />
      </el-form-item>

      <template v-if="form.classify === 2">
        <el-form-item label="用工人数"  prop="limitNum">
          <el-input-number
            :disabled="isEdit"
            max="100"
            style="width: 100%;"
            placeholder="请输入项目用工人数(最多100人)"
            v-model="form.limitNum"
            :min="0"
            :max="100"
          />
        </el-form-item>

        <el-form-item label="截至日期"  prop="jiezhiDate">
          <el-date-picker :disabled="isEdit" value-format="YYYY-MM-DD" placeholder="请选择报名截至日期" v-model="form.jiezhiDate" :disabled-date="disabledDate"   />
        </el-form-item>
      </template>

      <el-form-item label="项目内容"   prop="proContent">
        <el-input
          class="left-placeholder"
          :rows="10"
          placeholder="请输入项目职责、项目要求等，建议使用短句并分条列出，如下：
  项目职责：
    1、.....
    2、.....
  项目要求：
    1、.....
    2、.....
  "
          type="textarea"
          :disabled="isEdit"
          v-model="form.proContent"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <template v-if="props.action === ActionEnum.PROJECT_VERFY">
          <el-button @click="onVerifyEdit">修改</el-button>
          <el-button @click="approval(2)" :loading="loading2">拒绝</el-button>
          <el-button @click="approval(3)" type="primary" :loading="loading3">同意</el-button>
        </template>
        <template v-else>
          <el-button :loading="loading" @click="onSubmit(0)">保存</el-button>
          <el-button type="primary" :loading="loading" @click="onSubmit(1)">保存并发布</el-button>
        </template>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { Method } from 'axios';
  import { TaskInfo, ActionEnum } from '../types';
  import {selBtByMs} from "@/api/settlementManagement/settlementPayment/index"
  import { HttpStatus } from '@/enums/RespEnum';
  import { param } from '@/utils';
  import moment from 'moment';
  import useUserStore from '@/store/modules/user'
  const { proxy } = getCurrentInstance() as ComponentInternalInstance

 /**
   * 业务类型
  */
  const {wxfe_bus_type} =  toRefs<any>(proxy?.useDict("wxfe_bus_type"));
  const cascaderRef = ref();
  const businessTypeOptions = ref();

  const disabledDate = (inputDate)=>{
      return inputDate.getTime() <= Date.now();
  }


  interface TreeNode {
    value: number | string;
    label: string;
    children?: TreeNode[]; // 使用 ? 表示children是可选的
  }

  function findNodeById(tree: TreeNode[], value: number | string): TreeNode | null {
    for (const node of tree) {
      if (node.value == value) {
        return node;
      }
      if (node.children && node.children.length > 0) {
        const foundNode = findNodeById(node.children, value);
        if (foundNode) {
          return foundNode;
        }
      }
    }
    return null;
  }
  interface Props {
    action: ActionEnum;
    open: boolean;
    title: string;
  }


  const props = withDefaults(defineProps<Props>(), {
    action: ActionEnum.PROJECT_ADD,
    open: false,
    title: '创建项目'
  });

  const handleChange = (value:any, selectedData:any)=>{
      // value 是选中的值的数组
      // selectedData 是选中项的数据数组，每个对象都包含 value 和 label
      console.log(value); // 打印选中项的 label
    }
  const emits = defineEmits(['onFinish'])


  const disabled = computed(() => {
    let disabled: boolean = false;
    if (props.action === ActionEnum.PROJECT_ADD) {
      disabled = false
    } else if (props.action === ActionEnum.PROJECT_EDIT) {
      disabled = true
    } else if (props.action === ActionEnum.PROJECT_VERFY) {
      disabled = true
    }
    return false;
  })


  const getBusType = async(defaultProvider:any)=>{
      let params = {
        merId:defaultProvider.merId,
        sydId:defaultProvider.sydId
      }


      selBtByMs(params).then((res)=>{
        if(res.code == 200){
            let busTypes = res.data;
            let busArray = [] ;
           busArray =  busTypes.map(item =>{
              return {
                label:item.dictLabel,
                value:parseInt(item.dictValue)
              }
            });
            businessTypeOptions.value = busArray;
        }
      })
  }

const open = ()=>{

  let defaultProvider = useUserStore().defaultProvider;
  if(defaultProvider && defaultProvider.merId){
    getBusType(defaultProvider);
  }
  if (props.action === ActionEnum.PROJECT_ADD) {
      form.value = {
            proContent: '',
            name: '',
            cost: null,
            costMax: null,
            busType: '',
            classify: 1,
            industry: '',
            limitNum: null,
            jiezhiDate: '',
            id: null,  // 项目id
            merId: '',
            merNo: '',
      }
  }
}

  const setVisible = (open: boolean) => {
    dialogVisible.value = open
  }

  const onVerifyEdit = async () => {
    isEdit.value = false;
    // if (readOnly.value) {
    //   // 第二次点击修改
    //   // 运营商 服务商 修改项目接口
    //   const data = await useRequest('/payment/task/editInfo', 'put', { data: {
    //     ...form
    //   } }, { immediate: true })
    //   console.log('data333', data);

    // } else {
    //   // 第一次点击
    // readOnly.value = false
    // }
  }

  const { data: industryOptions } = useRequest('/system/industry/selList', 'GET', {
    }, { immediate: true })

  const dialogVisible = ref(false)

  const loading = ref(false);
  const loading2 = ref(false)
  const loading3 = ref(false)

  interface FormData {
      proContent: string;
      name: string;
      cost: number;
      costMax: number;
      busType: 1 | 2 | '';
      classify: string | number;
      industry: string;
      limitNum: number,
      jiezhiDate: string;
      id: string;  // 项目id
      merId: string | number;
      merNo: string | number;
  }

  const form = ref<FormData>({
      proContent: '',
      name: '',
      cost: null,
      costMax: null,
      busType: '',
      classify: 1,
      industry: '',
      limitNum: null,
      jiezhiDate: '',
      id: null,  // 项目id
      merId: '',
      merNo: '',
  })


  const costValidation = (rule: any, value: number, callback: any) => {

    if(!form.value.cost){
      callback(new Error("请输入最小金额"));
    }

    if (form.value.cost > value) {
      callback(new Error("最小金额不能大于最大金额"));
    } else {
      callback();
    }
  };


  const jiezhiDateValidation = (rule: any, value: any, callback: any)=>{
      let today = moment().format('YYYY-MM-DD');
      if(today >= value){
         callback(new Error("截止日期不能小于当前日期"));
      }else{
        callback();
      }
  }


  const rules = ref({
    busType: [{ required: true, message: "请选择业务类型", trigger: "blur" }],
    name: [{ required: true, message: "请输入项目标题", trigger: "blur" }],
    industry: [{ required: true, message: "请选择行业", trigger: "blur" }],
    classify: [{ required: true, message: "请选择项目类型", trigger: "blur" }],
    costMax:[{ required: true, validator: costValidation,    trigger: "blur"}],
    proContent: [{ required: true, message: "请输入项目内容", trigger: "blur" }],



    // busType: [{ required: true, message: "请选择业务类型", trigger: "blur" }],
    // newPassword: [{ required: true, message: "新密码不能为空", trigger: "blur" }, {
    //   min: 6,
    //   max: 20,
    //   message: "长度在 6 到 20 个字符",
    //   trigger: "blur"
    // }],
    // confirmPassword: [{ required: true, message: "确认密码不能为空", trigger: "blur" }, {
    //   required: true,
    //   validator: equalToPassword,
    //   trigger: "blur"
    // }]
  });




  const formRef = ref<ElFormInstance>();

/**
 * @param { 2 | 3 } verifyStatus
 * 2 拒绝
 * 3 同意
*/
    const approval = async (verifyStatus: 2 | 3) => {


    let selNodes = cascaderRef.value.getCheckedNodes()[0].pathLabels;
    if(verifyStatus ==2){
      loading2.value = true;
    }else if(verifyStatus == 3){
      loading3.value = true;
    }

    let params = {
        id:form.value.id,
        opVerifyStatus:verifyStatus
    };

    if(!isEdit.value){
      if(form.value.classify == 1){
        //派单
        params.name = form.value.name;
        params.industry = form.value.industry.join(",");
        params.industryName = selNodes.join(",");
        params.proContent = form.value.proContent;

      }else if(form.value.classify == 2){
        //抢单.
        params.name = form.value.name;
        params.industry = form .value.industry.join(",");
        params.industryName = selNodes.join(",");
        params.proContent = form.value.proContent;
        params.limitNum = form.value.limitNum;
        params.jiezhiDate = form.value.jiezhiDate;
      }
    }
    const { response } = await useRequest('/payment/task/check', 'PUT', {
      data: params
    }, { immediate: true })
    if(verifyStatus ==2){
      loading2.value = false;
    }else if(verifyStatus == 3){
      loading3.value = false;
    }
    if (response?.value?.code === HttpStatus.SUCCESS) {
      emits('onFinish', response);
      dialogVisible.value = false;
      ElMessage.success(response?.value?.msg);

    }

  }


  const radioGroupChangeHandler = (val)=>{


      if(val == 1){
        //派单
        rules.value = {
            busType: [{ required: true, message: "请选择业务类型", trigger: "blur" }],
            name: [{ required: true, message: "请输入项目标题", trigger: "blur" }],
            industry: [{ required: true, message: "请选择行业", trigger: "blur" }],
            classify: [{ required: true, message: "请选择项目类型", trigger: "blur" }],
            costMax:[{ required: true,    validator: costValidation,    trigger: "blur"}],
            proContent: [{ required: true, message: "请输入项目内容", trigger: "blur" }],
          }

      }else if(val == 2){
        //抢单
        rules.value = {
            busType: [{ required: true, message: "请选择业务类型", trigger: "blur" }],
            name: [{ required: true, message: "请输入项目标题", trigger: "blur" }],
            industry: [{ required: true, message: "请选择行业", trigger: "blur" }],
            classify: [{ required: true, message: "请选择项目类型", trigger: "blur" }],
            cost: [{ required: true, message: "请输入项目总金额(元)", trigger: "blur" }],
            jiezhiDate: [{ required: true, message: "请选择报名截至日期", trigger: "blur" },{ required: true,    validator: jiezhiDateValidation,    trigger: "blur"}],
            limitNum: [{ required: true, message: "请输入项目用工人数(最多100人)", trigger: "blur" }],
            proContent: [{ required: true, message: "请输入项目内容", trigger: "blur" }],


          }

      }

  }


  const currentNode = computed(() => findNodeById(industryOptions.value as TreeNode[], form.industry))

  const onSubmit = (taskStatus: 0 | 1 = 0) => {
      formRef?.value!.validate(async(valid) => {
          if (valid) {
              loading.value = true
              let defaultProvider = useUserStore().defaultProvider;
              // const node = findNodeById(industryOptions.value as TreeNode[],  form.industry)
              let selNodes = cascaderRef.value.getCheckedNodes()[0].pathLabels;
              console.log('currentNode', currentNode);

              const submitData = {
                ...form.value,
                industry:form.value.industry.join(","),
                industryName: selNodes.join(","),
                sydId: defaultProvider.sydId,
                merId: defaultProvider.merId,
                merNo: defaultProvider.merNo,
                sydNo: defaultProvider.sydNo,
                cost:form.value.cost?form.value.cost*100:form.value.cost,
                costMax:form.value.costMax?form.value.costMax*100:form.value.costMax,
                status: 1,
                taskStatus
              }

              const { id: taskId } = submitData
              let url: string, requestMethod: Method;
              if (taskId) {
                url = '/payment/task/edit'
                requestMethod = 'PUT'
              } else {
                url = '/payment/task/add';
                requestMethod = 'POST'
              }

              const { response } = await useRequest(url, requestMethod, { data: submitData }, { immediate: true })
              if (response.value.code === 200) {
                dialogVisible.value = false
                formRef.value.resetFields();

              }
              emits('onFinish', response)
              loading.value = false
          }
      })
  }

  const setFormData = (data:any) => {
    // Object.keys(form).forEach((key) => {
    //     form[key] = data[key]
    //   })
      form.value.id = data.id;
      form.value.busType = data.busType;
      form.value.name = data.name;
      form.value.classify = data.classify;
      form.value.industry = data.industry?data.industry.split(","):'';
      if(form.value.classify == 1){
        form.value.cost = data.cost/100;
        form.value.costMax = data.costMax/100;
      }else{
        form.value.cost = data.cost/100;
      }

      form.value.limitNum = data.limitNum;
      form.value.proContent = data.proContent;
      form.value.jiezhiDate = data.jiezhiDate;
  }

  const openModal = () => {
    dialogVisible.value = true
  }

  const readOnly = ref(false)
  const isEdit = ref(false);

  defineExpose({
    onEdit: (row: TaskInfo) => {
      openModal()
      setFormData(row)
    },
    onVerify: (row: TaskInfo) => {
      getBusType(row);
      openModal()
      setFormData(row)
      readOnly.value = true
      isEdit.value = true
    },
    setVisible
  })

  onMounted(() => {
    // const data = useRequest('/payment/proInfo/selBtByMs', 'GET', {
    //   params: {
    //     sydId: 1,
    //     merId: 1
    //   }
    // }, { immediate: true })

  })
</script>
<style scoped>
  .dialog-footer button:first-child {
      margin-right: 10px;
  }

  .el-textarea__inner {
    text-align: left;
  }
</style>
